<template>
  <Card istitle>
    <template #title>管理员信息</template>
    <template>
      <el-row><span>管理员ID:</span>{{ userInfo.id }}</el-row>
      <el-row><span>账号:</span>{{ userInfo.account }}</el-row>
      <el-row><span>用户组:</span>{{ userInfo.userGroup }}</el-row>
      <el-row><span>创建时间:</span>{{ userInfo.ctime | setTimer }}</el-row>
      <el-row class="userImg">
        <span>管理员头像:</span>
        <el-upload
          class="avatar-uploader"
          action="http://172.16.20.167:5000/users/avatar_upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <el-button type="primary" round size="mini" @click="editImg"
          >确认修改图像</el-button
        >
      </el-row>
    </template>
  </Card>
</template>

<script>
import local from '@/utils/local.js'
import { editUserImg } from '@/api/user.js'
import { error } from '@/utils/messagebox.js'
export default {
  data() {
    return {
      userInfo: {},
      imageUrl: '',
      url: ''
    }
  },
  created() {
    this.userInfo = JSON.parse(local.get('userInfo'))
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.url = res.imgUrl
    },
    beforeAvatarUpload(file) {
      const arr = ['image/jpeg', 'image/gif']
      const isJPG = arr.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 修改用户图片
    async editImg() {
      // 判断图像框是否有图片
      if (this.url) {
        // 发送请求
        const { code } = await editUserImg({
          imgUrl: this.url
        })
        // 判断是否更改成功
        if (code === 0) {
          this.$bus.$emit('updataImg')
        }
      } else {
        error.call(this, '请选择新图片')
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.avatar-uploader {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    margin-right: 20px;
  }
  .el-upload:hover {
    border-color: #409eff;
  }
}
/deep/.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
/deep/.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.el-row {
  padding: 20px 0;
  border-bottom: 2px solid #ebeef5;
  span {
    padding-right: 15px;
  }
}
.userImg {
  display: flex;
  align-items: center;
  .el-button {
    align-self: flex-end;
  }
}
</style>
